/*
 * Copyright 2002-2017 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.deservel.wxopen.service.Impl;

import com.deservel.wxopen.constant.MessageConsts;
import com.deservel.wxopen.model.message.request.BaseRequest;
import com.deservel.wxopen.model.message.response.TextResponse;
import com.deservel.wxopen.service.CoreService;
import com.deservel.wxopen.common.utils.MDUtils;
import com.deservel.wxopen.common.utils.XmlUtils;
import org.dom4j.DocumentException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.Date;
import java.util.Map;

/**
 * @author DeserveL
 * @date 2017/7/3 17:10
 * @since 1.0.0
 */
@Service
public class CoreServiceImpl implements CoreService {

    private static Logger log = LoggerFactory.getLogger(CoreServiceImpl.class);

    // 与接口配置信息中的Token要一致
    private static String token = "deservel";

    @Override
    public String checkSignature(String signature, String nonce, String timestamp, String echostr) {
        String[] arr = new String[]{token, nonce, timestamp};
        //将token、timestamp、nonce三个参数进行字典序排序
        try {
            Arrays.sort(arr);
        } catch (Exception e) {
            log.error("初始验证参数错误");
            return "";
        }
        StringBuilder content = new StringBuilder();
        for (int i = 0; i < arr.length; i++) {
            content.append(arr[i]);
        }
        String s = MDUtils.sha1Security(content.toString());
        if (s != null && signature != null) {
            log.info("初始验证通过");
            return s.equals(signature.toUpperCase()) ? echostr : "";
        } else {
            log.error("初始验证失败");
            return "";
        }
    }

    @Override
    public String postMessage(String requestXml) {
        Map<String, String> requestMap;
        try {
            requestMap = XmlUtils.fromXmlToMap(requestXml);
        } catch (DocumentException e) {
            log.error("消息解析异常" + e.getMessage());
            return "";
        }
        System.out.println(requestMap);
        BaseRequest baseRequest = XmlUtils.fromXmlToBeanWithOutAnnotations(requestXml, BaseRequest.class);
        TextResponse textResponse = new TextResponse();
        textResponse.setFromUserName(baseRequest.getToUserName());
        textResponse.setToUserName(baseRequest.getFromUserName());
        textResponse.setCreateTime(new Date().getTime());
        textResponse.setMsgType(MessageConsts.REQ_MESSAGE_TYPE_TEXT);
        String msgType = baseRequest.getMsgType();

        switch (msgType) {
            //文本
            case MessageConsts.REQ_MESSAGE_TYPE_TEXT:
                textResponse.setContent("伙计，你这是一个文本消息啊" + System.getProperty("line.separator"));
                break;
            //图片
            case MessageConsts.REQ_MESSAGE_TYPE_IMAGE:
                break;
            //语音
            case MessageConsts.REQ_MESSAGE_TYPE_VOICE:
                break;
            //视频
            case MessageConsts.REQ_MESSAGE_TYPE_VIDEO:
                break;
            //小视频
            case MessageConsts.REQ_MESSAGE_TYPE_SHORTVIDEO:
                break;
            //地理位置
            case MessageConsts.REQ_MESSAGE_TYPE_LOCATION:
                break;
            //链接
            case MessageConsts.REQ_MESSAGE_TYPE_LINK:
                break;
            //事件推送
            case MessageConsts.REQ_MESSAGE_TYPE_EVENT:
                break;
            default:
                textResponse.setContent("伙计，你这是一个别的消息啊" + System.getProperty("line.separator"));
        }
        return XmlUtils.fromModelToXml(textResponse);
    }
}
